package app.sys.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

public class ExcelUtil {
    public static void download(HttpServletResponse response, String title, Class t, List list) throws IOException, IllegalAccessException, InstantiationException {
        // 设置响应内容
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        // 设置编码格式
        response.setCharacterEncoding("UTF-8");
        //设置文件名
        String fileName = URLEncoder.encode(title, "UTF-8").replaceAll("\\+", "%20");
        //设置响应头
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        //获取写出流
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), t).build();
        // 创建sheet
        WriteSheet writeSheet = EasyExcel.writerSheet("sheet").build();
        // 读出
        excelWriter.write(list, writeSheet);
        // 关闭流
        excelWriter.finish();
    }
}
